<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      class="dialog"
      :close-on-click-modal="false"
      center
      width="400px">
      <div class="login-form" v-show="MODAL_STATUS === STATUS_LOGIN">
        <h3 style="margin: auto;text-align: center; padding-bottom: 10px">登&nbsp;&nbsp;录</h3>
        <el-form :model="member" status-icon :rules="rules" ref="member" class="demo-ruleForm">
          <el-form-item prop="mobile">
            <el-input v-model="member.mobile" autocomplete="off" placeholder="登录手机号12345678912"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" v-model="member.password" autocomplete="off" placeholder="登录密码a12345"></el-input>
          </el-form-item>
          <el-form-item prop="imageCode">
            <el-input v-model="member.imageCode" autocomplete="off" placeholder="验证码">
              <template slot="append"><img id="image-code" alt="验证码" @click="loadImageCode()"/></template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="login(member)">登&nbsp;&nbsp;&nbsp;&nbsp;录</el-button>
          </el-form-item>
          <el-form-item class="login-form-bottom">
            <span class="login-form-bottom-left">
              <el-checkbox v-model="remember">记住密码</el-checkbox>
            </span>
            <span class="login-form-bottom-right">
              <el-link :underline="false" @click="toForgetDialog()">忘记密码</el-link>
              <span> | </span>
              <el-link :underline="false" @click="toRegisterDialog()">我要注册</el-link>
            </span>
          </el-form-item>
        </el-form>
      </div>
      <div class="forget-form" v-show="MODAL_STATUS === STATUS_FORGET">
        <h3 style="margin: auto;text-align: center; padding-bottom: 10px">忘记密码</h3>
        <el-form :model="memberForget" status-icon :rules="rules" ref="memberForget" class="demo-ruleForm">
          <el-form-item prop="mobile">
            <el-input v-model="memberForget.mobile" autocomplete="off" placeholder="手机号"></el-input>
          </el-form-item>
          <el-form-item prop="smsCode">
            <el-input v-model="memberForget.smsCode" autocomplete="off" placeholder="手机验证码123456">
              <template slot="append">
                <el-button class="el-button-sms" v-if="countdown === 0" @click="sendSmsForForget()">&nbsp;&nbsp;发送验证码&nbsp;&nbsp;</el-button>
                <el-button class="el-button-sms" v-else disabled>重新发送({{countdown}})</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" v-model="memberForget.password" autocomplete="off" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item prop="checkPass">
            <el-input type="password" v-model="memberForget.checkPass" autocomplete="off"
                      placeholder="确认密码"></el-input>
          </el-form-item>
          <el-form-item prop="checkPass">
            <el-button class="el-button-reset" type="primary" @click="resetPassword(memberForget)">重&nbsp;&nbsp;&nbsp;&nbsp;置</el-button>
          </el-form-item>
          <el-form-item class="login-form-bottom">
            <div class="login-form-bottom-link" >
              <el-link :underline="false" @click="toLoginDialog()">我要登录</el-link>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="register-form" v-show="MODAL_STATUS === STATUS_REGISTER">
        <h3 style="margin: auto;text-align: center; padding-bottom: 10px">注&nbsp;&nbsp;册</h3>
        <el-form :model="memberRegister" status-icon :rules="rules" ref="memberRegister" class="demo-ruleForm">
          <el-form-item prop="mobile">
            <el-input v-model="memberRegister.mobile" autocomplete="off" placeholder="手机号"></el-input>
          </el-form-item>
          <el-form-item prop="smsCode">
            <el-input v-model="memberRegister.smsCode" autocomplete="off" placeholder="手机验证码123456">
              <template slot="append">
                <el-button class="el-button-sms" v-if="countdown === 0" @click="sendSmsForRegister()">&nbsp;&nbsp;发送验证码&nbsp;&nbsp;</el-button>
                <el-button class="el-button-sms" v-else disabled>重新发送({{countdown}})</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="loginName">
            <el-input v-model="memberRegister.loginName" autocomplete="off" placeholder="昵称"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" v-model="memberRegister.password" autocomplete="off" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item prop="checkPass">
            <el-input type="password" v-model="memberRegister.checkPass" autocomplete="off"
                      placeholder="确认密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="el-button-register" type="primary" @click="register()">注&nbsp;&nbsp;&nbsp;&nbsp;册</el-button>
          </el-form-item>
          <el-form-item class="register-form-bottom">
            <div class="register-form-bottom-link" >
              <el-link :underline="false" @click="toLoginDialog()">我要登录</el-link>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  import Notify from "../util/notify";

  export default {
    name: 'the-login-dialog',
    data() {
      let _this = this
      let validator = {
        checkMobile: (rule, value, callback) => {
          if (!value) {
            return callback(new Error('电话号码不能为空'));
          }
          if (!Pattern.validateMobile(value)) {
            callback(new Error('电话号码格式不正确'));
          } else {
            callback();
          }
        },
        checkSmsCode: (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入短信验证码'));
          }
          if (!Pattern.validateMobileCode(value)) {
            callback(new Error('短信验证码格式不正确'));
          } else {
            callback();
          }
        },
        loginName: (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入昵称'));
          }
          if (!Pattern.validateName(value)) {
            callback(new Error('昵称长度为6到20，包括中文，字母，数字，下划线'))
          } else {
            callback()
          }
        },
        validatePass: (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入密码'));
          } else {
            if (!Pattern.validatePasswordWeak(value)) {
              callback(new Error('密码最少6位，包括至少1字母，1个数字'));
            }
            if (_this.memberForget.checkPass !== '' || _this.memberRegister.checkPass !== '') {
              _this.$refs['memberRegister'].validateField('checkPass');
            }
            callback();
          }
        },
        validatePass2: (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请再次输入密码'));
          } else if ((value !== _this.memberForget.password && _this.memberForget.password !== '')
            || (value !== _this.memberRegister.password && _this.memberRegister.password !== '')) {
            callback(new Error('两次输入密码不一致!'));
          } else {
            callback();
          }
        },
        checkImageCode: (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入验证码'));
          }
          if (!Pattern.validateImageCode(value)) {
            callback(new Error('验证码格式不正确'));
          } else {
            callback()
          }
        }
      }
      return {
        // 模态框内容切换：登录、注册、忘记密码
        STATUS_LOGIN: "STATUS_LOGIN",
        STATUS_REGISTER: "STATUS_REGISTER",
        STATUS_FORGET: "STATUS_FORGET",
        MODAL_STATUS: "",

        dialogVisible: false,

        member: {
          mobile: '',
          password: '',
          imageCode: ''
        },
        memberForget: {
          mobile: '',
          smsCode: '',
          password: '',
          checkPass: ''
        },
        memberRegister: {
          mobile: '',
          smsCode: '',
          loginName: '',
          password: '',
          checkPass: ''
        },
        rules: {
          mobile: [
            {validator: validator.checkMobile, trigger: 'blur'}
          ],
          smsCode: [
            {validator: validator.checkSmsCode, trigger: 'blur'}
          ],
          loginName: [
            {validator: validator.loginName, trigger: 'blur'}
          ],
          password: [
            {validator: validator.validatePass, trigger: 'blur'}
          ],
          checkPass: [
            {validator: validator.validatePass2, trigger: 'blur'}
          ],
          imageCode: [
            {validator: validator.checkImageCode, trigger: 'blur'}
          ]
        },

        imageCodeToken: '',
        remember: true,
        countdown: 0
      }
    },
    mounted() {
      let _this = this
      _this.toLoginDialog()

      /**
       * 监听事件总线, 在detail.vue的enroll()中调用
       */
      _this.$event.$on('openLoginDialog', () => {
        _this.openLoginDialog()
      })
    },
    methods: {
      /**
       * 打开登录注册窗口
       */
      openLoginDialog() {
        let _this = this
        setTimeout(() => {
          _this.loadImageCode()
        }, 100)
        _this.dialogVisible = true
      },

      //---------------登录框、注册框、忘记密码框切换-----------------

      /**
       * 切换登录框
       */
      toLoginDialog() {
        let _this = this;

        // 从缓存中获取记住的用户名密码，如果获取不到，说明上一次没有勾选“记住我”
        let rememberMember = LocalStorage.get(LOCAL_KEY_REMEMBER_MEMBER);
        if (rememberMember) {
          _this.member = rememberMember;
        }

        // 显示登录框时就刷新一次验证码图片
        _this.loadImageCode();

        _this.MODAL_STATUS = _this.STATUS_LOGIN
      },

      /**
       * 切换注册框
       */
      toRegisterDialog() {
        let _this = this;
        _this.MODAL_STATUS = _this.STATUS_REGISTER
      },

      /**
       * 切换忘记密码框
       */
      toForgetDialog() {
        let _this = this;
        _this.MODAL_STATUS = _this.STATUS_FORGET
      },
      
      //-----------------------------------------------------------

      /**
       * 登录
       */
      login () {
        let _this = this

        _this.$refs['member'].validate((valid) => {
          if (valid) {
            //  如果是第一次登录, 那么走正常流程, 输入的密码被加盐加密一次给后端
            //  如果勾选了记住我, 第二次登录, 这个_this.member则是从缓存中取出的, 密码已经是加盐加密过后的了, 则密码不需要再加盐加密, 直接传给后端
            let md5 = hex_md5(_this.member.password)
            let rememberMember = LocalStorage.get(LOCAL_KEY_REMEMBER_MEMBER) || {}
            if (md5 !== rememberMember.md5) {
              //  密码加密(MD5)
              _this.member.password = hex_md5(_this.member.password + KEY)
            }

            _this.member.imageCodeToken = _this.imageCodeToken;

            _this.$axios.post(process.env.VUE_APP_SERVER + '/business/web/member/login', _this.member).then((resp) => {
              if (resp.data.success) {
                //  登录成功
                Notify.success('登录成功')
                let loginMember = resp.data.content
                //  保存用户信息到SessionStorage
                Tool.setLoginMember(loginMember)
                //  是否勾选'记住我'功能
                if (_this.remember) {
                  let md5 = hex_md5(_this.member.password)  // 将经过一次加盐加密的密码再加密一次
                  LocalStorage.set(LOCAL_KEY_REMEMBER_MEMBER, {
                    mobile: loginMember.mobile,
                    password: _this.member.password,  //  保存的经过一次加密的密码
                    md5: md5
                  })
                } else  {
                  LocalStorage.set(LOCAL_KEY_REMEMBER_MEMBER, null)
                }

                // 调用the-header的setLoginMember()
                _this.$parent.setLoginMember(loginMember)
                // 事件总线: 调用detail里的getEnroll()
                _this.$event.$emit('getEnroll')
                _this.dialogVisible = false
              } else {
                Notify.warning(resp.data.message)
                _this.member.password = ''
                _this.loadImageCode()
              }
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

      /**
       * 重置密码
       */
      resetPassword() {
        let _this = this

        _this.$refs['memberForget'].validate((valid) => {
          if (valid) {
            _this.memberForget.password = hex_md5(_this.memberForget.password + KEY)

            // 调服务端密码重置接口
            _this.$axios.post(process.env.VUE_APP_SERVER + '/business/web/member/reset-password', _this.memberForget).then((resp)=>{
              if (resp.data.success) {
                Notify.success("密码重置成功")
                _this.toLoginDialog()
              } else {
                Notify.warning(resp.data.message)
              }
            }).catch((resp)=>{
              console.log("error：", resp)
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

      /**
       * 注册
       */
      register() {
        let _this = this

        _this.$refs['memberRegister'].validate((valid) => {
          if (valid) {
            _this.memberRegister.password = hex_md5(_this.memberRegister.password + KEY);

            _this.$axios.post(process.env.VUE_APP_SERVER + '/business/web/member/register', _this.memberRegister).then((response) => {
              let resp = response.data
              if (resp.success) {
                Notify.success("注册成功")
                _this.toLoginDialog()
              } else {
                Notify.warning(resp.message)
              }
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

      /**
       * 发送注册短信
       */
      sendSmsForRegister() {
        let _this = this

        // 单独校验手机号字段
        _this.$refs['memberRegister'].validateField('mobile', error => {
          if (Tool.isEmpty(error)) {
            let sms = {
              mobile: _this.memberRegister.mobile,
              use: SMS_USE.REGISTER.key
            }

            _this.$axios.get(process.env.VUE_APP_SERVER + '/business/web/member/is-mobile-exist/' + _this.memberRegister.mobile).then((resp)=>{
              if (resp.data.success) {
                Notify.warning("手机号已被注册")
              } else {
                // 调服务端发送短信接口
                _this.sendSmsCode(sms)
              }
            })
          }
        });
      },

      /**
       * 发送忘记密码短信
       */
      sendSmsForForget() {
        let _this = this

        // 单独校验手机号字段
        _this.$refs['memberForget'].validateField('mobile', error => {
          if (Tool.isEmpty(error)) {
            let sms = {
              mobile: _this.memberForget.mobile,
              use: SMS_USE.FORGET.key
            };

            _this.$axios.get(process.env.VUE_APP_SERVER + '/business/web/member/is-mobile-exist/' + _this.memberForget.mobile).then((resp)=>{
              if (resp.data.success) {
                _this.sendSmsCode(sms)
              } else {
                Notify.warning("手机号未注册")
              }
            });
          }
        })
      },

      /**
       * 发送短信
       */
      sendSmsCode(sms) {
        let _this = this

        // 调服务端发短信接口
        _this.$axios.post(process.env.VUE_APP_SERVER + '/business/web/sms/send', sms).then((res)=> {
          let response = res.data;
          if (response.success) {
            Notify.success("短信已发送")
            // 开始倒计时
            _this.countdown = 60
            _this.setTime()
          } else {
            Notify.warning(response.message)
          }
        })
      },

      /**
       * 倒计时
       * @param btnId
       */
      setTime() {
        let _this = this
        if (_this.countdown === 0) {
          return
        } else {
          _this.countdown--
        }
        setTimeout(() => {
          _this.setTime()
        }, 1000)
      },

      /**
       * 加载图形验证码
       */
      loadImageCode() {
        let _this = this;
        _this.imageCodeToken = Tool.uuid(8);
        $('#image-code').attr('src', process.env.VUE_APP_SERVER + '/business/web/kaptcha/image-code/' + _this.imageCodeToken)
        // _this.$axios.get(process.env.VUE_APP_SERVER + '/business/web/kaptcha/image-code/' + _this.imageCodeToken).then((resp) => {
        //   console.log(resp.data)
        //   _this.imageCodeSrc = resp
        // })
      },
    }
  }
</script>

<style lang="less">
  .dialog {
    h3 {
      margin-bottom: 10px;
      height: 66px;
    }

    .login-form {


      #image-code {
        height: 40px;
      }

      .el-input-group__append {
        padding: 0;
        border: none;
      }

      .el-button {
        padding: 10px 150px;
        font-size: 16px;
      }

      .login-form-bottom {

        .login-form-bottom-left {
          margin-right: 140px;
        }

        .login-form-bottom-right {
          color: #a5acb2;
        }
      }
    }

    .forget-form {

      .el-input-group__append {
        background-color: #409EFF;
        border-color: #409EFF;
        color: #FFF;
      }

      .is-disabled {
        color: #C0C4CC;
        background-color: #EBEEF5;
        border-color: #EBEEF5;
      }

      .el-button-sms {
        height: 40px;
        width: 116.08px;
        border-radius: 0 4px 4px 0;
      }

      .el-button-reset {
        padding: 10px 150px;
        font-size: 16px;
      }

      .login-form-bottom {
        display: flex;
        justify-content: center;

        .login-form-bottom-link {
        }
      }
    }

    .register-form {

      .el-input-group__append {
        background-color: #409EFF;
        color: #FFF;
      }

      .is-disabled {
        color: #C0C4CC;
        background-color: #EBEEF5;
        border-color: #EBEEF5;
      }

      .el-button-sms {
        height: 40px;
        width: 116.08px;
        border-radius: 0 4px 4px 0;
      }

      .el-button-register {
        padding: 11px 150px;

        font-size: 16px;
      }

      .register-form-bottom {
        display: flex;
        justify-content: center;

        .register-form-bottom-link {
        }
      }
    }
  }
</style>
